<template>
  <el-select
    v-model="selectValue"
    :remote="remote"
    :clearable="clearable"
    :filterable="filterable"
    :reserve-keyword="reserveKeyword"
    :remote-method="remoteMethod"
    :loading="loading"
    :disabled="disabled"
    style="width: 100%;"
    @change="handleChangeSelect"
  >
    <template v-if="isArrayOptions">
      <el-option
        v-for="(label, value) of options"
        :key="value"
        :value="value"
        :label="label"
      />
    </template>
    <template v-else>
      <el-option
        v-for="item in options"
        :key="optionProps(item).value"
        :value="optionProps(item).value"
        :label="optionProps(item).label"
      />
    </template>
  </el-select>
</template>
<script>
export default {
  props: {
    value: {
      type: String | Number,
      default: ''
    },
    loading: {
      type: Boolean,
      default: false
    },
    clearable: {
      type: Boolean,
      default: true
    },
    remoteMethod: {
      type: Function
    },
    getOption: {
      type: Function,
      default: item => [item.value, item.label]
    },
    options: {
      type: Function | Object,
      default: () => []
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      selectValue: this.value,
      filterable: !!this.remoteMethod,
      remote: !!this.remoteMethod,
      reserveKeyword: !!this.remoteMethod
    }
  },
  watch: {
    value (val) {
      this.selectValue = val
    }
  },
  computed: {
    isArrayOptions () {
      return typeof this.options == 'object' && this.options != null && Object.prototype.toString.call(this.options) == '[object Object]'
    }
  },
  methods: {
    // 下拉选择change
    handleChangeSelect () {
      this.$emit('update:value', this.selectValue)
      this.$emit('change', this.selectValue)
    },
    optionProps (item) {
      const [value, label] = this.getOption(item) ?? []
      return { value, label }
    }
  }
}
</script>
